//
//  WGQMyQRCodeViewController.m
//  meiang_edu
//
//  Created by gq w on 2018/10/12.
//  Copyright © 2018 com.meiang.meiang_edu. All rights reserved.
//  我的w二维码

#import "WGQMyQRCodeViewController.h"

@interface WGQMyQRCodeViewController ()

@property (nonatomic,strong) UIImageView * imageView;

@end

@implementation WGQMyQRCodeViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.edgesForExtendedLayout = UIRectEdgeBottom;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.extendedLayoutIncludesOpaqueBars = NO;
    self.title = @"我的二维码";
    [self creatQRCode];
}

- (void)creatQRCode
{
    //创建过滤器
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    //过滤器恢复默认
    [filter setDefaults];
    //给过滤器添加数据
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    NSString *string = [NSString stringWithFormat:@"%@,user,%@",userinfo.ID,userinfo.ID];
    //将NSString格式转化成NSData格式
    NSData * data = [string dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    [filter setValue:data forKeyPath:@"inputMessage"];
    //获取二维码过滤器生成的二维码
    CIImage *image = [filter outputImage];
    //将获取到的二维码添加到imageview上
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(30 * kScale, ([UIScreen mainScreen].bounds.size.height - 300 * kScale - [UIApplication sharedApplication].statusBarFrame.size.height - self.navigationController.navigationBar.frame.size.height)/2, 300 * kScale, 300 * kScale)];
    [self.view addSubview:self.imageView];
    self.imageView.image = [self createNonInterpolatedUIImageFormCIImage:image withSize:300 * kScale];
}

- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size
{
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 1.创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}

@end
